const express = require('express');
const path = require('path');
const fs = require('fs');
const app = express();
const bodyParser = require('body-parser');
const session = require('express-session');
const serverRender = require('./util/server-render');

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))

app.use(session({
  maxAge: 10 * 60 * 1000,
  name: 'tid',
  resave: false,
  saveUninitialized: false,
  secret: 'I will teach you'
}))

app.use('/api/user', require('./util/user-api'))
app.use('/api', require('./util/proxy'))

const isDev = process.env.NODE_ENV === 'development';
if(!isDev) {
  const serverEntry = require('../dist/server-entry');
  const template = fs.readFileSync(path.join(__dirname, '../dist/server.ejs'),'utf8');
  app.use('/public', express.static(path.join(__dirname, '../dist')));
  app.get('*', (req, res, next) => {
    serverRender(serverEntry, template, req, res).catch(next);
  })
} else {
  const devStatic = require('./util/dev.static');
  devStatic(app);
}

app.use(function(error, req, res, next) {
  console.log(error);
  res.status(500).send(error);
})

app.listen(7001, () => {
  console.log('Success start server');
})